package org.oschina.api.user.menu.dao;

import java.util.List;
import org.oschina.Constants;
import org.oschina.api.BaseDAO;
import org.oschina.api.user.menu.model.UserMenu;
import org.oschina.api.user.menu.vo.UserMenuVo;
import org.springframework.stereotype.Repository;

@Repository
public class UserMenuDAO extends BaseDAO {

	private final String findVo[]={"id","icon","text","url","main","parent","`index`"};
	
	/**
	 * 返回	
	 * @return
	 */
	public List<UserMenuVo> findVo()
	{
		return getQueryHelper().query_cache(findVo, null, new String[]{"ORDER BY `index`"}, null, UserMenuVo.class,-1,-1);
	}
	
	/**
	 * 根据权限返回
	 * @param role
	 * @return
	 */
	public List<UserMenuVo> findVoByRole(int role)
	{
		return getQueryHelper().query_cache(findVo, new String[]{"id IN (SELECT ubr.menu FROM "+Constants.DB_USER_MENU_ROLE+" ubr WHERE ubr.role=?)"}, 
				new String[]{"ORDER BY `index`"}, new Object[]{role}, UserMenuVo.class,-1,-1);
	}
	
	/**
	 * 更新
	 * @param menu
	 * @return
	 */
	public int update(UserMenu menu)
	{
		return (int) getQueryHelper().update_cache(new String[]{"icon=?","text=?","url=?","parent=?","main=?","`index`=?"}, new String[]{"id=?"}, 
				new Object[]{menu.getIcon(),menu.getText(),menu.getUrl(),menu.getParent(),menu.getMain(),menu.getIndex(),menu.getId()}, UserMenuVo.class);
	}
	
	/**
	 * 创建
	 * @param menu
	 * @return
	 */
	public int create(UserMenu menu)
	{
		return (int) getQueryHelper().insert_cache(new String[]{"id","icon","text","url","parent","main","`index`","create_time"},
				new Object[]{menu.getId(), menu.getIcon(), menu.getText(), menu.getUrl(),menu.getParent(),menu.getMain(),menu.getIndex(), menu.getCreate_time()}, UserMenuVo.class);
	}
	
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	public int delete(int id)
	{
		return (int) getQueryHelper().delete_cache(new String[]{"id=?"}, new Object[]{id}, UserMenuVo.class);
	}
	
	/**
	 * 根据ID返回
	 * @param id
	 * @return
	 */
	public UserMenuVo findVoById(int id)
	{
		UserMenuVo menuVo=(UserMenuVo) getCacheHelper().hget(getKey(Constants.CACHE_USER_MENU, id), UserMenuVo.class);
		if(menuVo!=null)
			return menuVo;
		
		return _findById(id);
	}
	private UserMenuVo _findById(int id)
	{
		return (UserMenuVo) getQueryHelper().queryForObject_cache(findVo, new String[]{"id=?"}, new Object[]{id}, UserMenuVo.class);
	}
}